package com.pansoft.kline.helper;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigFutureBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.utilcode.util.SPUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.pansoft.openplanet.constant.MarketConstant.BOURSE_RATE_URL;
import static com.pansoft.openplanet.constant.MarketConstant.KEY_MARKET_RATE;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_CONFIG_URL;

//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;

/**
 * 交易所汇率
 *
 * @autor yqs
 * @date 2018/11/21 9:59
 **/
public class BtcKanConfigAndRateHelper {

    private static final String TAG = "BtcKanConfigAndRateHelper";

    private static JSONObject rateObject;
    private static Timer timer;


    public static void initConfig() {
        getBtcKanConfig();
        //getRate(null);
        startTimerTask();
    }

    public static void release() {
        rateObject = null;
        stopTask();

    }


    //定时获取汇率，10分钟一次吧
    private static void startTimerTask() {
        stopTask();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                requestRate(null);
            }
        }, 0, 10 * 60 * 1000);
    }

    private static void stopTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /**
     * 获取各个交易所的汇率信息
     *
     * @param callBack
     */
    public static JSONObject getRate(final RateCallBack callBack) {
        if (rateObject != null) {
            if (callBack != null) {
                callBack.obtainRate(true, rateObject);
            }
            return rateObject;
        }
        //网络请求汇率信息
        requestRate(callBack);

        //读取sp存储的汇率
        String json = SPUtils.getInstance().getString(KEY_MARKET_RATE);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
            rateObject = jsonObject.getJSONObject("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rateObject;
    }

    /**
     * 请求汇率
     *
     * @param callBack
     */
    private static void requestRate(final RateCallBack callBack) {
        HashMap<String, String> hashMap = new HashMap<>();
        JFCommonRequestManager.getInstance(AppContext.getInstance()).requestGetByAsyn(TAG, BOURSE_RATE_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int code = jsonObject.getInt("code");
                    if (code == 0) {
                        rateObject = jsonObject.getJSONObject("data");
                        //存到sp中
                        SPUtils.getInstance().put(KEY_MARKET_RATE, result);
                        if (callBack != null) {
                            callBack.obtainRate(true, rateObject);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.obtainRate(false, null);
                    }

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                //获取本地存储的汇率
                String json = SPUtils.getInstance().getString(KEY_MARKET_RATE);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    rateObject = jsonObject.getJSONObject("data");
                    if (rateObject != null && callBack != null) {
                        callBack.obtainRate(true, rateObject);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //返回失败
                if (callBack != null) {
                    callBack.obtainRate(false, null);
                }
            }
        });
    }


    public interface RateCallBack {

        void obtainRate(boolean isSuccess, JSONObject rateObject);

    }


    /**
     * 请求配置信息
     * 每次打开应用的时候请求一次
     */
    public static void getBtcKanConfig() {
        // https://x.szsing.com:443/v2/quote/price/m_config?version=
        if (DaoSessionUtil.getInstance().getConfigSiteBeanDao().count() <= 0) {
            EnvironmentVariable.setProperty("bk_config_version", "");
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("version", EnvironmentVariable.getProperty("bk_config_version", ""));

        JFCommonRequestManager.getInstance(AppContext.getInstance()).requestGetByAsyn(TAG, MARKET_CONFIG_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    parserConfig(result);

                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
            }
        });
    }

    private static void parserConfig(final String result) {
        //数据量太大，放到线程里执行net.sf.json 解析太慢
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
//                LogUtils.i("开始保存btckan config信息");
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    int code = jsonObject.getInt("code");
                    if (code == 0) {
                        if (jsonObject.get("data") instanceof JSONArray) {
                            //表示没有新的配置信息
                            return;
                        }
                        JSONObject dataObject = jsonObject.getJSONObject("data");
                        String version = dataObject.optString("version", "");
                        EnvironmentVariable.setProperty("bk_config_version", version);

                        JSONObject sitesObject = dataObject.getJSONObject("sites");
                        JSONObject coinsObject = dataObject.getJSONObject("coins");
                        JSONObject marketsObject = dataObject.getJSONObject("markets");
                        JSONObject futuresObject = dataObject.getJSONObject("futures");

                        List<ConfigSiteBean> configSiteBeanList = new ArrayList<>();
                        List<ConfigCoinBean> configCoinBeanList = new ArrayList<>();
                        List<ConfigMarketBean> configMarketBeanList = new ArrayList<>();
                        List<ConfigFutureBean> futureBeanList = new ArrayList<>();

                        Iterator<String> sitesKeys = sitesObject.keys();
                        while (sitesKeys.hasNext()) {
                            ConfigSiteBean configSiteBean = new ConfigSiteBean();
                            String key = sitesKeys.next();
                            JSONObject valueObject = sitesObject.getJSONObject(key);
                            configSiteBean.setUniqueKey(key);
                            configSiteBean.setTitle(valueObject.optString("title", ""));
                            configSiteBean.setFee(valueObject.optString("fee", ""));
                            configSiteBean.setLogo(valueObject.optString("logo", ""));
                            configSiteBean.setUrl(valueObject.optString("url", ""));

                            configSiteBeanList.add(configSiteBean);
                        }

                        Iterator<String> coinsKeys = coinsObject.keys();
                        while (coinsKeys.hasNext()) {
                            ConfigCoinBean configCoinBean = new ConfigCoinBean();
                            String key = coinsKeys.next();
                            JSONObject valueObject = coinsObject.getJSONObject(key);
                            configCoinBean.setCoinKey(key);
                            configCoinBean.setName(valueObject.optString("name", ""));
                            configCoinBean.setCoin_name_other(valueObject.optString("coin_name_other", ""));
                            configCoinBean.setTitle(valueObject.optString("title", ""));
                            configCoinBean.setSymbol(valueObject.optString("symbol", ""));
                            configCoinBean.setIndexSites(valueObject.optString("index_sites", ""));
                            configCoinBean.setIndexMarketId(valueObject.optString("index_market_id", ""));
                            configCoinBeanList.add(configCoinBean);
                        }

                        Iterator<String> marketsKeys = marketsObject.keys();
                        while (marketsKeys.hasNext()) {
                            ConfigMarketBean marketBean = new ConfigMarketBean();
                            String key = marketsKeys.next();
                            JSONObject valueObject = marketsObject.getJSONObject(key);
                            marketBean.setMarketId(key);
                            marketBean.setCoin(valueObject.optString("coin", ""));
                            marketBean.setCurrency(valueObject.optString("currency", ""));
                            marketBean.setCs(valueObject.getJSONObject("show").optString("cs", ""));
                            marketBean.setDc(valueObject.getJSONObject("show").optString("dc", ""));
                            marketBean.setTicker(valueObject.getJSONObject("show").optString("ticker", ""));

                            marketBean.setFee(valueObject.optString("fee", ""));
                            marketBean.setFuture(valueObject.optString("future", ""));
                            marketBean.setSite(valueObject.optString("site", ""));
                            marketBean.setType(valueObject.optString("type", ""));
                            configMarketBeanList.add(marketBean);
                        }
                        Iterator<String> futuresKeys = futuresObject.keys();
                        while (futuresKeys.hasNext()) {
                            ConfigFutureBean futureBean = new ConfigFutureBean();
                            String key = futuresKeys.next();
                            JSONObject valueObject = futuresObject.getJSONObject(key);
                            futureBean.setId(key);
                            futureBean.setTitle(valueObject.optString("title", ""));
                            futureBeanList.add(futureBean);
                        }

                        //清空数据
                        DaoSessionUtil.getInstance().getConfigSiteBeanDao().deleteAll();
                        DaoSessionUtil.getInstance().getConfigCoinBeanDao().deleteAll();
                        DaoSessionUtil.getInstance().getConfigMarketBeanDao().deleteAll();
                        DaoSessionUtil.getInstance().getConfigFutureBeanDao().deleteAll();

                        //保存数据库
                        DaoSessionUtil.getInstance().getConfigSiteBeanDao().insertInTx(configSiteBeanList);
                        DaoSessionUtil.getInstance().getConfigCoinBeanDao().insertInTx(configCoinBeanList);
                        DaoSessionUtil.getInstance().getConfigMarketBeanDao().insertInTx(configMarketBeanList);
                        DaoSessionUtil.getInstance().getConfigFutureBeanDao().insertInTx(futureBeanList);
//                        LogUtils.i("保存btckan config信息成功");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }


}



